/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Panier.java
 *
 * Created on 5 janv. 2009, 04:14:25
 */

package fr.miage.shopping.presentation.panel;

import fr.miage.shopping.dao.traitements.LigneCommandeDao;
import fr.miage.shopping.dao.traitements.ProduitDao;
import fr.miage.shopping.metier.entite.Client;
import fr.miage.shopping.metier.entite.Commande;
import fr.miage.shopping.metier.entite.Lignecommande;
import fr.miage.shopping.metier.entite.Produit;
import fr.miage.shopping.metier.impl.CommandeBusinessServiceImpl;
import fr.miage.shopping.metier.impl.ProduitBusinessServiceImpl;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author romain
 */
public class Panier extends javax.swing.JPanel {

    DefaultTableModel model;
    private Client client;

    /** Creates new form Panier */
    public Panier(Client client) {
        this.client=client;
        initComponents();
        remplirTable();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Nom du produit", "Quantité", "Prix du produit", "Total du produit"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class, java.lang.Double.class, java.lang.Double.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Total Commande en € :");

        jTextField1.setEditable(false);
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jButton2.setText("Supprimer ligne du panier");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setText("Mettre à jour le panier");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText("Commander");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(jButton2))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(16, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(244, Short.MAX_VALUE)
                .addComponent(jButton3)
                .addGap(36, 36, 36))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(12, 12, 12)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(137, 137, 137)
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton2))
                .addContainerGap(75, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(12, 12, 12)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(182, Short.MAX_VALUE)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed


    }//GEN-LAST:event_jTextField1ActionPerformed
    public void ajouterElement(Vector v) {
        model.addRow(v);
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        int indice_selection;
        Object[] choix = { "Oui", "Non" };

        indice_selection=jTable1.getSelectedRow();
        if (indice_selection==-1)
        {
            JOptionPane.showMessageDialog(null,"Vous n'avez selectionné aucun produit dans le panier !","Suppression de produuit dans le panier",JOptionPane.WARNING_MESSAGE);
        }
        else{


       int choix_utilisateur=JOptionPane.showOptionDialog(null, "Voulez vous supprimer le produit selectionné ?", "Enlever un produit du panier",JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,null, choix, choix[0]);
       if (choix_utilisateur==0)
            {
                String nom_produit=(String)model.getValueAt(indice_selection,0);
                model.removeRow(indice_selection);
                String message="Vous venez d'enlever le produit " + nom_produit + " du panier !";
                JOptionPane.showMessageDialog(null,message,"Suppression d'un produit du panier",JOptionPane.WARNING_MESSAGE);
                model.fireTableDataChanged();
                if (model.getRowCount()!=0)
                {calculTotal();}
                else{jTextField1.setText("panier vide");}
            }
        }

        jTable1.clearSelection();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        if (model.getRowCount()!=0)
        {
            calculTotauxTableau();
            calculTotal();
        }
        else{
             JOptionPane.showMessageDialog(null,"Le panier est vide","Panier vide",JOptionPane.WARNING_MESSAGE);
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

        CommandeBusinessServiceImpl cbs= new CommandeBusinessServiceImpl();
        Commande cmd= new Commande();
        cmd.setDateCommande(new Date());
        cmd.setClient(client);
        cbs.createCommande(cmd);
        String message = "La commande a été créé et son montant est de " + jTextField1.getText() + " euros";
        JOptionPane.showMessageDialog(null,message,"Commande confirmée",JOptionPane.INFORMATION_MESSAGE);
        ProduitBusinessServiceImpl bs = new ProduitBusinessServiceImpl();

         for (int i = 0; i < model.getRowCount(); i++)
        {

              String nom_prod=(String)(model.getValueAt(i,0));
              Produit p= new Produit();
              p.setNomProd(nom_prod);
              p = ProduitDao.selectProduitByName(p);
              int qte=Integer.parseInt((String)(model.getValueAt(i,1)));
             // Double prix=Double.valueOf(""+model.getValueAt(i,2));
             
              Lignecommande lc= new Lignecommande();
              lc.setCommande(cmd);
              lc.setProduit(p);
              lc.setQuantite(qte);
              LigneCommandeDao.insertLigneCommande(lc);

        }

        JOptionPane.showMessageDialog(null,"L'ensemble des lignes de commandes ont été enregistrées","Ligne de Commande confirmée",JOptionPane.INFORMATION_MESSAGE);


    }//GEN-LAST:event_jButton3ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables


    public void remplirTable()
    {
        Object []col = {"Nom du produit", "Quantité", "Prix du produit","Total produit"};
        model= new DefaultTableModel(col,0);
        //ajoutElement("Portable","1","2.5");
        jTable1.setModel(model);
        calculTotal();
    }

    public void ajoutElement(String nomprod,String qte,String prixprod)
    {
        double totalprod = Integer.parseInt(qte)*Double.valueOf(prixprod);
        Object []row={nomprod,qte,prixprod,totalprod};
        model.addRow(row);
        model.fireTableDataChanged();
        
    }

    public void calculTotal()
    {
     double resultat=0;

    for (int i = 0; i < model.getRowCount(); i++){
          resultat = resultat + (Double)model.getValueAt(i, 3); }
          resultat = (Math.floor(resultat*100.0))/100;
          jTextField1.setText(Double.toString(resultat));
    }

    public void calculTotauxTableau()
    {
        int quantite;
        String prix_prod;
        double total;

        for (int i = 0; i < model.getRowCount(); i++)
        {
            String qte=(String)(model.getValueAt(i,1));
            quantite=Integer.parseInt(qte);
            prix_prod=""+model.getValueAt(i,2);
            total=Double.valueOf(prix_prod)*quantite;
            model.setValueAt(total, i, 3);

        }

    }
    
}
